﻿using System.Web.Mvc;
using System.Text;

namespace SlamCms.Web.Mvc
{
    public class JavascriptFunctionResult : ActionResult
    {
        private Encoding contentEncoding;
        private string contentType;
        private string javascriptFunction;

        public JavascriptFunctionResult(string javascriptFunction)
        {
            this.javascriptFunction = javascriptFunction;
        }

        public Encoding ContentEncoding
        {
            get
            {
                return this.contentEncoding;
            }

            set
            {
                this.contentEncoding = value;
            }
        }

        public string ContentType
        {
            get
            {
                return this.contentType;
            }

            set
            {
                this.contentType = value;
            }
        }

        public string JavascriptFunction
        {
            get
            {
                return this.javascriptFunction;
            }

            set
            {
                this.javascriptFunction = value;
            }
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;

            if (!string.IsNullOrEmpty(this.ContentType))
                response.ContentType = this.ContentType;
            else
                response.ContentType = "text/html";

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;

            var sb = new StringBuilder();
            sb.Append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>");
            sb.Append("<script type=\"text/javascript\">");
            sb.Append(this.javascriptFunction);
            sb.Append("</script>");
            sb.Append("</head></html>");

            response.Write(sb.ToString());
        }
    }
}